﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodStuff.Heartbeat.Core;
using GoodStuff.Heartbeat.Core.Sensors;
using System.Threading;
using GoodStuff.Heartbeat.Core.Monitors;
using GoodStuff.Heartbeat.Core.Notifiers;
using System.ServiceModel;
using System.ServiceModel.Description;
using GoodStuff.Heartbeat.Core.Configuration;
using System.Xml;
using System.Data.Linq;

namespace GoodStuff.Heartbeat
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(Environment.CurrentDirectory);
            string path = Environment.CurrentDirectory;

            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            EnsureDatabase();


            //load the configuration.
            XmlConfigurationLoader loader = new XmlConfigurationLoader();
            XmlDocument doc = new XmlDocument();
            doc.Load("configuration.xml");

            Settings.components = loader.LoadConfiguration(doc);

            Engine engine = new Engine(Settings.components);
            engine.OnError += (s, e) => { Console.WriteLine("ERROR: " + e.Error.Message); };
            engine.OnTrace += (s, e) => { Console.WriteLine(e.Message); };
            engine.Start();

            Console.WriteLine("Press [enter] to stop");
            Console.ReadLine();

            engine.Stop();


        }

        private static void EnsureDatabase()
        {
            string connString = GoodStuff.ConfigurationHelper.GetConnectionString();
            if (connString.Contains("|DataDirectory|"))
            {
                string dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
                connString = connString.Replace("|DataDirectory|", dataDirectory);
            }

            using (Core.Data.DataClassesDataContext ctx = new Core.Data.DataClassesDataContext(connString))
            {
                if (ctx.DatabaseExists() == false)
                {
                    ctx.CreateDatabase();
                }
            }
        }
    }
}
